const app = getApp()

Page({
  data: {
    certificates: [],
    stats: {},
    page: 1,
    perPage: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.loadCertificates()
    this.loadStats()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载证书列表
  loadCertificates(refresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      page: refresh ? 1 : this.data.page,
      per_page: this.data.perPage
    }

    wx.request({
      url: `${app.globalData.baseUrl}/certificates/my`,
      method: 'GET',
      data: params,
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const newCertificates = res.data.data.items
          const total = res.data.data.total
          const currentPage = res.data.data.page
          const hasMore = currentPage * this.data.perPage < total

          this.setData({
            certificates: refresh ? newCertificates : [...this.data.certificates, ...newCertificates],
            page: currentPage + 1,
            hasMore: hasMore,
            loading: false
          })

          if (refresh) {
            wx.stopPullDownRefresh()
          }
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载证书失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        this.setData({ loading: false })
        if (refresh) {
          wx.stopPullDownRefresh()
        }
      }
    })
  },

  // 加载统计数据
  loadStats() {
    wx.request({
      url: `${app.globalData.baseUrl}/certificates/stats`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ stats: res.data.data })
        }
      },
      fail: (err) => {
        console.error('加载证书统计失败:', err)
      }
    })
  },

  // 加载更多
  loadMore() {
    this.loadCertificates()
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadCertificates(true)
    this.loadStats()
  },

  // 查看证书
  viewCertificate(e) {
    const certId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/certificate-detail/certificate-detail?id=${certId}`
    })
  },

  // 下载证书
  downloadCertificate(e) {
    const certId = e.currentTarget.dataset.id
    
    wx.showLoading({ title: '生成证书中...' })
    
    wx.request({
      url: `${app.globalData.baseUrl}/certificates/${certId}/download`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const { download_url } = res.data.data
          
          // 下载文件
          wx.downloadFile({
            url: download_url,
            success: (downloadRes) => {
              if (downloadRes.statusCode === 200) {
                // 保存到相册
                wx.saveImageToPhotosAlbum({
                  filePath: downloadRes.tempFilePath,
                  success: () => {
                    wx.showToast({
                      title: '证书已保存到相册',
                      icon: 'success'
                    })
                  },
                  fail: (err) => {
                    console.error('保存证书失败:', err)
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail: (err) => {
              console.error('下载证书失败:', err)
              wx.showToast({
                title: '下载失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '下载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取下载链接失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 跳转到考试页面
  goToExams() {
    wx.switchTab({
      url: '/pages/exams/exams'
    })
  }
}) 